package com.shop.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author Song Yinghui
 * @date 2019/12/9
 * @Version 1.0
 */
public class NettyClient {

    private static Channel channel = null;

    private static Bootstrap bootstrap ;

    private static EventLoopGroup group ;

    public static void init() throws InterruptedException {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });

        //模拟2000个netty链接，此处不能用sync() 因为sync()会阻塞线程
        for (int i = 0; i < 2000; i++) {
            bootstrap.connect("127.0.0.1", 8080);
        }

        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8080).sync();
        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("this is client request...".getBytes())).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }

    public static void main(String[] args) throws InterruptedException {
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("client close...");
            group.shutdownGracefully();
        }));
        init();
    }
}
